package com.hgy.stack;

import java.util.Scanner;

public class LinkedListStackDemo {
    public static void main(String[] args) {
        LinkedListStack<Integer> stack = new LinkedListStack<Integer>();
        String key = "";
        boolean loop = true;
        Scanner scanner = new Scanner(System.in);

        while (loop){
            System.out.println("show：表示显示栈");
            System.out.println("exit：退出程序");
            System.out.println("push：表示添加数据到栈");
            System.out.println("pop：表示从栈取出数据");
            key = scanner.next();
            switch (key){
                case "show":
                    stack.list();
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                case "push":
                    stack.push(scanner.nextInt());
                    break;
                case "pop":
                    try {
                        System.out.println("栈取出的数据为"+stack.pop());
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                default:
                    System.out.println("输入的命令错误，请重新输入！");
            }
        }
        System.out.println("程序结束！");
    }
}

class LinkedListStack<T>{
    private LinkedNode<T> head = new LinkedNode<T>();

    public LinkedNode<T> getHead() {
        return head;
    }

    public boolean isEmpty(){
        return head.getNext() == null;
    }

    public void push(T value){
        LinkedNode<T> newNode = new LinkedNode<T>(value);
        newNode.setNext(head.getNext());
        head.setNext(newNode);
    }

    public T pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空，没有数据");
        }
        T res = head.getNext().getValue();
        head.setNext(head.getNext().getNext());
        return res;
    }

    public T top(){
        if (isEmpty()){
            throw new RuntimeException("栈空，没有数据");
        }
        T res = head.getNext().getValue();
        return res;
    }

    public void list(){
        if (isEmpty()){
            System.out.println("栈空~");
            return;
        }
        System.out.println("栈顶");
        LinkedNode temp = head.getNext();
        while (temp != null){
            System.out.println(temp.getValue());
            temp = temp.getNext();
        }
        System.out.println("栈底");
    }
}

class LinkedNode<T>{
    private T value;
    private LinkedNode<T> next;

    public LinkedNode(){}

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    public LinkedNode(T value){
        this.value = value;
    }


    public LinkedNode<T> getNext() {
        return next;
    }

    public void setNext(LinkedNode<T> next) {
        this.next = next;
    }
}
